package com.dsz.apiinterface.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.dsz.apiinterface.model.User;
import com.dsz.apiinterface.utils.SignUtil;

import java.util.HashMap;

public class MyClient {
    private String accessKey;
    private String secretKey;

    public MyClient(String accessKey, String secretkey) {
        this.accessKey = accessKey;
        this.secretKey = secretkey;
    }

    public static void main(String[] args) {
        MyClient myClient = new MyClient("dsz", "abcdefg");
        myClient.testGet("dushangzhi");
        myClient.testPost("zhangsan");
        User user = new User();
        user.setUsername("lisi");
        myClient.testPost2(user);
    }

    private HashMap<String, String> getHeaderMap(String body) {
        HashMap<String, String> map = new HashMap<>();
        map.put("accessKey", accessKey);
//        map.put("secretkey", secretkey);
        map.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        map.put("nonce", RandomUtil.randomNumbers(100));
        map.put("body",body);
        map.put("sign", SignUtil.getSign(body,secretKey));
        return map;
    }


    public String testGet(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String res = HttpUtil.get("http://localhost:8081/name", hashMap);
        System.out.println(res);
        return res;
    }

    public String testPost(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String res = HttpUtil.post("http://localhost:8081/name", hashMap);
        System.out.println(res);
        return res;
    }

    public String testPost2(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8081/name/post")
                .body(jsonStr)
                .addHeaders(getHeaderMap(jsonStr))
                .execute();
        int status = httpResponse.getStatus();
        System.out.println(status);
        String body = httpResponse.body();
        System.out.println(body);
        return body;
    }
}
